// 结构数据定义
package result

import (
	"encoding/json"
	"fmt"
	"gin_test/global"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Result 结构体
type Result struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// Success 成功结构体
func Success(c *gin.Context, data interface{}) {
	if data == nil {
		data = gin.H{}
	}
	res := Result{}
	res.Code = int(ApiCode.Success)
	res.Message = ApiCode.GetMessage(ApiCode.Success)
	res.Data = data
	jsonStr, _ := json.Marshal(res)
	global.Log.Infoln(fmt.Sprintf("return: %s", string(jsonStr)))
	c.JSON(http.StatusOK, res)
}

// Failed 失败结构体
func Failed(c *gin.Context, code int, message string, data interface{}) {
	if data == nil {
		data = gin.H{}
	}
	res := Result{}
	res.Code = code
	if message != "" {
		res.Message = message
	} else {
		res.Message = ApiCode.GetMessage(code)
	}
	res.Data = data
	jsonStr, _ := json.Marshal(res)
	global.Log.Infoln(fmt.Sprintf("return: %s", string(jsonStr)))
	c.JSON(http.StatusOK, res)
}
